
const getEnv = function getEnv() {
	try {
		if(self && self.self === self) {
			getEnv = x => true;
            return true;
		} else {
			getEnv = x => false;
            getEnv = x => false;
		}
	} catch(e) {
		getEnv = x => false;
        return false;
	}
};

const print = function (params, color) {
	if(getEnv()) {
		// window下
		color = color || '#0089ff';
		if(params && typeof params === 'object') {
			console.table(params);
		} else {
			console.log('%c' + params, `
				font-size: 16px;
				color: white;
				background-color: ${ color }
			`);
		}
	} else {
		// node下
		color = `[${ color || '92' }m`;
		if(params && typeof params === 'object') {
			console.log(params);
		} else {
			console.log('\033' + color + params + ' \033[39m');
		}
	}
};

// 模拟传统面向对象接口
const Interface = class Interface {
    constructor(name, methods) {
        if(arguments.length < 2) {
            throw Error(`您只传入了${ arguments.length }个参数，参数少于2`);
        }
        this.name = name;
        this.methods = [];
        for(let i = 0, len = methods.length; i < len; i++) {
            if(typeof methods[i] !== 'string') {
                throw new Error(`传入的第${ i + 1 }个方法名有误，希望传入一个字符串作为方法名`);
            }

            this.methods.push(methods[i]);
        }
    }

    ensureImplements(obj) {
        let 
            i = 0,
            length = arguments.length,
            intf = null;

        if(length < 2) {
            throw Error(`最少传入2个参数`);
        }

        for(i = 1; i < length; i++) {
            intf = arguments[i];
            if(intf instanceof this) {
                intf.methods.forEach((item, index) => {
                    if(typeof obj[item] !== 'function') {
                        throw new Error(`lose ${ intf.name }\'s ${ item } method.`);
                    }
                });
            } else {
                throw new Error(`Need interface class instance.`);
            }
        }
    }
};

// 将字符串里的数字包起来
const wrapperNumFromString = str => {
	return str.replace(/\d+/g, function (item, index, all) {
		return `<span>${item}</span>`;
	});
};

// 格式化日期
const formatDate = time => {
    let 
    	now = new Date(),
        old = new Date(time),
        timer = new Date(now.toLocaleDateString()).getTime(),
        hms = old.toTimeString().slice(0, 5);
    ;

    switch(true) {
        case now.getFullYear() !== old.getFullYear():
            let t = old.toLocaleDateString().split('/');
            return `${t[0]}年${t[1]}月${t[2]}日${hms}`;
        case timer - time <= 86400000:
            if(old.getDate() === now.getDate()) {
                return '今天' + hms;
            } else {
                return '昨天 ' + hms;
            }
        case timer - time <= 86400000 * 7:
            let _old = old.getDay(),
                _now = now.getDay(),
                week = ['一', '二', '三', '四', '五'];
            ;
            if(_old * (_now - _old) > 0){
                return '星期' + week[_old - 1] + hms;
            }
        default:
            return `${ (old.getMonth() + 1) }月${ old.getDate() }日${ hms }`;
        ;
    }
};

// 获取浏览器支持的动画事件名
const whichTransitionAndAnimationEvent = x => {
    let 
        el = document.createElement('fakeelement'),
        transitions = {
            'transition': 'transitionend',
            'OTransition': 'oTransitionEnd',
            'MozTransition': 'transitionend',
            'WebkitTransition': 'webkitTransitionEnd'
        },
        result = {
            transition: '',
            animation: ''
        };
    ;
    for(let t in transitions) {
        if(el.style[t] !== undefined) {
            result.transition = transitions[t];
            break;
        }
    }
    
    if(el.style['animation'] !== undefined) {
        result.animation = 'animationend';
    } else if(el.style['webkitAnimation'] !== undefined) {
        result.animation = 'webkitAnimationEnd';
    }
    return result;
};

// 获取一个随机key
const getRandomKey = num => {
    let 
        keyArr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A' ,'B' ,'C' ,'D' ,'E' ,'F' ,'G' ,'H' ,'I' ,'J' ,'K' ,'L' ,'M' ,'N' ,'O' ,'P' ,'Q' ,'R' ,'S' ,'T' ,'U' ,'V' ,'W' ,'X' ,'Y' ,'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
        length = keyArr.length,
        key = '';
    ;
    for(let i = 0; i < num; i++) {
        key += keyArr[Math.floor(Math.random() * length)];
    }
    return key;
};

// 格式化数字
const formatNumberGrounpWithThree = (num, groupLength = 3) => {
    let 
        numberString = num + '',
        stringLength = numberString.length;
    ;

    if(stringLength < groupLength + 1) {
        return numberString;
    }

    let 
        remainder = stringLength % groupLength,
        headerString = remainder ? numberString.slice(0, remainder) + ',' : '',
        reg = new RegExp('(\\d{' + groupLength + '}(?!$))', 'g');
    ;
    numberString = headerString + numberString.slice(remainder).replace(reg, '$1,');
    return numberString;
};

const namespace = function(name) {
    let 
        parts = name.split('.'),
        current = this;
    ;
    for(let i = 0, len = parts.length; i < len; i++) {
        if(!current[parts[i]]) {
            current[parts[i]] = {};
        }
        current = current[parts[i]];
    }
    return this;
};
module.exports = {
	getEnv,
	print,
	Interface,
	formatDate,
	wrapperNumFromString,
	getRandomKey,
	formatNumberGrounpWithThree,
	namespace
};